import os, sys
try:
  from selenium import webdriver
  import pyperclip
  import pyautogui
except:
  os.system("pip3 install --user pyperclip pyautogui pip install msedge-selenium-tools selenium==3.141")
  from selenium import webdriver
  import pyperclip
  import pyautogui
from selenium.webdriver.support import expected_conditions as ec
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.by import By
from time import sleep
import win32gui

class WindowMgr:
  def __init__ (self):
    self._handle = None
  def find_window(self, class_name, window_name=None):
    self._handle = win32gui.FindWindow(class_name, window_name)
  def _window_enum_callback(self, hwnd, wildcard):
    if re.match(wildcard, str(win32gui.GetWindowText(hwnd))) is not None:
      self._handle = hwnd
  def find_window_wildcard(self, wildcard):
    self._handle = None
    win32gui.EnumWindows(self._window_enum_callback, wildcard)
  def set_foreground(self):
    win32gui.SetForegroundWindow(self._handle)


def main(a):

  s= open(a, encoding='UTF8', mode='r')
  s7= open('trans.'+os.path.basename(a),encoding='UTF8',mode='w')
  s2= s.readlines()

  s3= []
  while s2:
    s4= next((s2[:n] for n in range(len(s2), 0, -1) if len(' '.join(s2[:n]))<5000), s2[:1])
    s3.append('\n'.join(s4))
    s2= s2[len(s4):]

  s6= []
  for i in range(len(s3)):
    s8=s3[i]
    if len(s8)>5000:
      s6.append('%s:\t%s\t...\t%s' %(len(s8), s8[:20], s8[-20:]))
  if len(s6)>0:
    print("存在超过5000字的分段，将会在翻译时出错，请重新分段")
    print('\n'.join(s6))
    sys.exit()

  main3_initialize()
  for i in s3[:0]:
    s9=main2(i)
    print(s9)
    s7.writelines([s5])
    
  s.close()
  s7.close()




def main2(a):
  # <https://developer.microsoft.com/en-us/microsoft-edge/tools/webdriver/#downloads>
  # 在设置里登录微软账户
  w = WindowMgr()
  w.set_foreground()
  s2 = WebDriverWait(main2.s, 10).until(
  ec.presence_of_element_located((By.CLASS_NAME, "er8xn")))
  #s2.click()
  w.find_window_wildcard(main2.s.title)
  pyperclip.copy('阿松大妈的阿大撒')
  pyautogui.hotkey('ctrl', 'v')
  #print("\tText Box")
  #sleep(2)
  s3 = WebDriverWait(main2.s, 10).until(
  ec.presence_of_element_located((By.CLASS_NAME, "J0lOec"))
  ).text
  print(s3)
  s4 = WebDriverWait(s, 10).until(
  ec.presence_of_element_located((By.CLASS_NAME, "GA2I6e")))
  s4.click()
  return s3
  sleep(10)


def main3_initialize():
  main2.s= webdriver.Edge(r"msedgedriver.exe")
  main2.s.get("https://translate.google.cn/",)

if __name__ == "__main__":
  for i in sys.argv[1:]:
    i=i.strip('\'\"\\').rstrip("/")
    main(i)
